package com.example.shiroredisdemo.config;

import com.example.shiroredisdemo.entity.*;
import com.example.shiroredisdemo.repository.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-06
 **/
@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private RolePermissionRepository rolePermissionRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("授权验证-----------");
        List<String> permissionList = new ArrayList();
        List<String> roleNameList= new ArrayList<>();
        User user = (User) principalCollection.fromRealm(this.getClass().getName()).iterator().next();
        Integer uid = user.getUid();
        List<UserRole> userRoleList = userRoleRepository.findByUid(uid);
        for(UserRole userRole:userRoleList){
            Role role = roleRepository.findByRid(userRole.getRid());
            roleNameList.add(role.getName());
            List<RolePermission> rolePermissionList = rolePermissionRepository.findByRid(userRole.getRid());
            for(RolePermission rolePermission:rolePermissionList){
                Permission permission = permissionRepository.findByPid(rolePermission.getPid());
                permissionList.add(permission.getName());
            }
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissionList);
        info.addRoles(roleNameList);
        return info;

    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("登陆认证----------");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)authenticationToken;
        String username = usernamePasswordToken.getUsername();
        User user = userRepository.findByUsername(username);
        return new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getName());
    }
}
